'use client';

import { queryRoleDetails } from '@/services/api';
import { useQuery } from '@tanstack/react-query';
import type { IRole } from '@/interfaces';
import Alert from '@/app/[locale]/alert/alert';
import { useContext } from 'react';
import { RoleAdminContext } from '@/contexts/admin/auth/role';
import AlertLoad from '@/app/[locale]/alert/load';
import QueryRoleInfo from '@/app/[locale]/admin/auth/role/detail/info';
import QueryRoleUsers from '@/app/[locale]/admin/auth/role/detail/users';
import QueryRolePermissions from '@/app/[locale]/admin/auth/role/detail/permissions';

export default function DetailsRoleAdminPage() {
  const context = useContext(RoleAdminContext);

  const queryRoleDetailsQuery = useQuery(
    ['/roles', context.detailItem?.id],
    async (context) => {
      return (await queryRoleDetails({
        id: context.queryKey[1] + '',
      })) as IRole;
    },
  );

  if (queryRoleDetailsQuery.data) {
    const data = queryRoleDetailsQuery.data;

    return (
      <div className="row">
        <div className="col">
          <div className="vstack gap-4">
            <QueryRoleInfo details={data} />

            <div className="row">
              <div className="col">
                <QueryRoleUsers details={data} />
              </div>
              <div className="col">
                <QueryRolePermissions details={data} />
              </div>
            </div>

            <div></div>
          </div>
        </div>
      </div>
    );
  }

  if (queryRoleDetailsQuery.error) {
    return <Alert type="error" message={queryRoleDetailsQuery.error} />;
  }

  return <AlertLoad />;
}
